package com.lianmai.chaincard.view;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.support.constraint.ConstraintLayout;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.lianmai.chaincard.R;
import com.lianmai.chaincard.utils.KeyBoardUtil;
import com.lianmai.chaincard.utils.RegexUtils;
import com.youth.xframe.base.XActivity;
import com.youth.xframe.utils.XRegexUtils;
import com.youth.xframe.utils.log.XLog;
import com.youth.xframe.utils.statusbar.XStatusBar;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 创建日期：2018/8/16 0016
 * 作者:Kite
 */
public class BaseActivity extends XActivity {

    private ImageView actionbarBack;

    private TextView actionbarTitle;

    private TextView textLeft;

    private TextView textRight;

    private ConstraintLayout actionbar;

    protected FrameLayout content;

    private View viewContent;

    @Override
    public int getLayoutId() {
        return 0;
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        //XStatusBar.setColor(this, getResources().getColor(R.color.app_theme), 0);
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        actionbar = viewContent.findViewById(R.id.actionbar);
        content = viewContent.findViewById(R.id.content);
        actionbarBack = viewContent.findViewById(R.id.actionbar_back);
        actionbarTitle = viewContent.findViewById(R.id.actionbar_title);
        textLeft = viewContent.findViewById(R.id.tv_left);
        textRight = viewContent.findViewById(R.id.tv_right);
        actionbarBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        textLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        textRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                advance(InvitationCodeActivity.class);
            }
        });
        isSixVersion();
    }

    @Override
    public void setContentView(int layoutResId) {
        viewContent = getLayoutInflater().inflate(R.layout.activity_base, null);
        FrameLayout content = (FrameLayout) viewContent.findViewById(R.id.content);
        View view = getLayoutInflater().inflate(layoutResId, null);
        content.addView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        super.setContentView(viewContent);
    }

    /**
     * 批量设置控件的显示状态
     *
     * @param isVisible 是否显示
     * @param views     控件集
     */
    public void setVisibility(boolean isVisible, View... views) {
        if (isVisible) {
            setVisibility(View.VISIBLE, views);
        } else {
            setVisibility(View.GONE, views);
        }
    }

    /**
     * 批量设置控件的显示状态
     *
     * @param visible 显示状态
     * @param views   控件集
     */
    public void setVisibility(int visible, View... views) {
        for (View view : views) {
            if (view.getVisibility() == visible) {
                continue;
            }

            view.setVisibility(visible);
        }
    }

    /**
     * 设置是否显示ActionBar
     *
     * @param isVisible 是否显示
     */
    public void hasActionBar(boolean isVisible) {
        actionbar.setVisibility(isVisible ? View.VISIBLE : View.GONE);
    }

    /**
     * 设置title背景图片
     *
     * @param resId 图片ID
     */
    public void setBackgroundByRes(int resId) {
        actionbar.setBackgroundResource(resId);
    }

    /**
     * 设置title背景颜色
     *
     * @param color 颜色值
     */
    public void setBackgroundByColor(String color) {
        actionbar.setBackgroundColor(Color.parseColor(color));
    }

    /**
     * 设置是否显示返回键
     *
     * @param isVisible 是否显示
     */
    public void hasBack(boolean isVisible) {
        if (isVisible) {
            actionbarBack.setVisibility(View.VISIBLE);
        } else {
            actionbarBack.setVisibility(View.INVISIBLE);
        }
    }

    /**
     * 设置返回键图片
     *
     * @param resId 图片ID
     */
    public void setBackRes(int resId) {
        actionbarBack.setImageResource(resId);
    }

    /**
     * 设置是否显示标题
     *
     * @param isVisible 是否显示
     */
    public void hasTitle(boolean isVisible) {
        actionbarTitle.setVisibility(isVisible ? View.VISIBLE : View.GONE);
    }

    /**
     * 设置标题
     *
     * @param resId 标题StringID
     */
    public void setTitle(int resId) {
        setTitle(getResources().getString(resId));
    }

    public void setLeft(int resId) {
        setTextLeft(getResources().getString(resId));
    }

    public void setRight(int resId) {
        setTextRight(getResources().getString(resId));
    }

    /**
     * 设置标题
     *
     * @param title 标题
     */
    public void setTitle(String title) {
        hasActionBar(true);
        actionbarTitle.setText(title);
    }

    public void setTextLeft(String text) {
        actionbarBack.setVisibility(View.INVISIBLE);
        textLeft.setVisibility(View.VISIBLE);
        textLeft.setText(text);
    }

    public void setTextRight(String text) {
        textRight.setVisibility(View.VISIBLE);
        textRight.setText(text);
    }

    /**
     * 设置标题颜色
     *
     * @param color 颜色值
     */
    public void setTitleColor(String color) {
        actionbarTitle.setTextColor(Color.parseColor(color));
    }

    /**
     * 设置标题颜色
     *
     * @param colorRes 颜色值
     */
    public void setTitleColor(int colorRes) {
        actionbarTitle.setTextColor(colorRes);
    }

    //region 隐藏软键盘

    // 获取点击事件
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        // TODO Auto-generated method stub
        /*if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);*/
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View view = getCurrentFocus();
            if (isHideInput(view, ev)) {
                HideSoftInput(view.getWindowToken());
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    // 判定是否需要隐藏
    private boolean isHideInput(View v, MotionEvent ev) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left
                    + v.getWidth();
            if (ev.getX() > left && ev.getX() < right && ev.getY() > top
                    && ev.getY() < bottom) {
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    // 隐藏软键盘
    private void HideSoftInput(IBinder token) {
        if (token != null) {
            InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            manager.hideSoftInputFromWindow(token,
                    InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    //endregion

    //region 跳转封装

    public void advance(Class<?> cls, Object... params) {
        this.advance(this.getAdvanceIntent(cls, params));
    }

    public void advance(String clsName, Object... params) {
        this.advance(this.getAdvanceIntent(clsName, params));
    }

    public void advance(Intent intent) {
        this.startActivity(intent);
        this.setStartActivityAnim();
    }

    public void advanceForResult(Class<?> cls, int requestCode, Object... params) {
        this.advanceForResult(this.getAdvanceIntent(cls, params), requestCode);
    }

    public void advanceForResult(String clsName, int requestCode, Object... params) {
        this.advanceForResult(this.getAdvanceIntent(clsName, params), requestCode);
    }

    public void advanceForResult(Intent intent, int requestCode) {
        this.startActivityForResult(intent, requestCode);
        this.setStartActivityAnim();
    }

    private void setStartActivityAnim() {
        if (Build.VERSION.SDK_INT >= 5) {
            this.overridePendingTransition(org.bining.footstone.R.anim.view_in_from_right, org.bining.footstone.R.anim.view_out_to_left);
        }
    }

    private Intent getAdvanceIntent(Class<?> cls, Object... params) {
        Intent intent = new Intent();
        intent.setClass(this, cls);
        return this.putParams(intent, params);
    }

    private Intent getAdvanceIntent(String clsName, Object... params) {
        Intent intent = new Intent();
        intent.setClassName(this, clsName);
        return this.putParams(intent, params);
    }

    private Intent putParams(Intent intent, Object... params) {
        if (intent != null && params != null && params.length > 0) {
            for (int i = 0; i < params.length; ++i) {
                intent.putExtra("p" + i, (Serializable) params[i]);
            }
        }
        return intent;
    }

    //endregion

    //region 获取验证码

    private TextView sendTextView;

    public String areaCode = "86";

    private int maxTime = 60;

    private Runnable resendRunnable = new Runnable() {
        @Override
        public void run() {
            maxTime--;
            if (maxTime < 1) {
                maxTime = 60;
                sendTextView.setText("重新发送");
                sendTextView.setTextColor(getResources().getColor(R.color.content_hint));
                sendTextView.setEnabled(true);
            } else {
                sendTextView.setText(String.format("%d秒后重新发送", maxTime));
                sendTextView.postDelayed(resendRunnable, 1000);
            }
        }
    };

    /**
     * 获取验证码
     */
    public void getCode(EditText phoneNumberEditText, TextView sendTextView) {
        this.sendTextView = sendTextView;
        if (TextUtils.isEmpty(phoneNumberEditText.getText())) {
            Toast.makeText(this, R.string.please_input_phone, Toast.LENGTH_SHORT).show();
            return;
        }
        String phoneNumber = phoneNumberEditText.getText().toString().trim().replaceAll(" ", "");
        if (!RegexUtils.checkMobile(phoneNumber)) {
            Toast.makeText(this, R.string.phone_is_error, Toast.LENGTH_SHORT).show();
            return;
        }
        KeyBoardUtil.closeKeyboard(phoneNumberEditText, this);
        String num = phoneNumber + areaCode;
        sendPhone(num);
    }

    private void sendPhone(String num) {
//        HttpUtils.sendCaptcha(num, new HttpCallback<String>() {
//            @Override
//            public void onSuccess(String s) {
//                //发送验证码成功
//                startCountDown();
//            }
//        });
        startCountDown();
    }

    private void startCountDown() {
        sendTextView.setText(String.format("%d秒后重新发送", maxTime));
        sendTextView.setTextColor(getResources().getColor(R.color.content_theme));
        sendTextView.setEnabled(false);
        sendTextView.postDelayed(resendRunnable, 1000);
    }

    //endregion

    private void isSixVersion() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            FlymeSetStatusBarLightMode(getWindow(), true);
            MIUISetStatusBarLightMode(getWindow(), true);
            changeStatusBarTextColor(true);
            XStatusBar.setColor(this, getResources().getColor(R.color.white), 0);
        } else {
            XStatusBar.setColor(this, getResources().getColor(R.color.content_btn_white), 0);
        }
    }

    /**
     * 设置状态栏图标为深色和魅族特定的文字风格
     * 可以用来判断是否为Flyme用户
     *
     * @param window 需要设置的窗口
     * @param dark   是否把状态栏字体及图标颜色设置为深色
     * @return boolean 成功执行返回true
     */
    public static boolean FlymeSetStatusBarLightMode(Window window, boolean dark) {
        boolean result = false;
        if (window != null) {
            try {
                WindowManager.LayoutParams lp = window.getAttributes();
                Field darkFlag = WindowManager.LayoutParams.class
                        .getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
                Field meizuFlags = WindowManager.LayoutParams.class
                        .getDeclaredField("meizuFlags");
                darkFlag.setAccessible(true);
                meizuFlags.setAccessible(true);
                int bit = darkFlag.getInt(null);
                int value = meizuFlags.getInt(lp);
                if (dark) {
                    value |= bit;
                } else {
                    value &= ~bit;
                }
                meizuFlags.setInt(lp, value);
                window.setAttributes(lp);
                result = true;
            } catch (Exception e) {
//                XLog.e(e.getMessage().toString());
            }
        }
        return result;
    }


    /**
     * 设置状态栏字体图标为深色，需要MIUIV6以上
     *
     * @param window 需要设置的窗口
     * @param dark   是否把状态栏字体及图标颜色设置为深色
     * @return boolean 成功执行返回true
     */
    public static boolean MIUISetStatusBarLightMode(Window window, boolean dark) {
        boolean result = false;
        if (window != null) {
            Class clazz = window.getClass();
            try {
                int darkModeFlag = 0;
                Class layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
                Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
                darkModeFlag = field.getInt(layoutParams);
                Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
                if (dark) {
                    extraFlagField.invoke(window, darkModeFlag, darkModeFlag);//状态栏透明且黑色字体
                } else {
                    extraFlagField.invoke(window, 0, darkModeFlag);//清除黑色字体
                }
                result = true;
            } catch (Exception e) {
//                XLog.e(e.getMessage().toString());
            }
        }
        return result;
    }


    private void changeStatusBarTextColor(boolean isBlack) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (isBlack) {
                getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);//设置状态栏黑色字体
            } else {
                getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);//恢复状态栏白色字体
            }
        }
    }
}
